<template>
  <div id="cesiumContainer">
    <!-- 自定义全屏按钮 -->
    <div id="btnFullscreen" class="btn-fullscreen cesium-viewer-fullscreenContainer"
         style="position:absolute;top: 2%; left: 2%; z-index: 1;"></div>
    <!-- 自定义HOME按钮 -->
    <div id="btnHome" class="btn-home" style="position:absolute; top: 1.8%; left: 5%; z-index: 1;"></div>
    <!-- 自定义基本图层选择按钮 -->
    <div id="btnBaseLayerPicker" class="btn-baseLayerPicker"
         style="position:absolute; top: 1.8%; right: 9%; z-index: 1;"></div>
  </div>
</template>

<script setup>
import {onMounted, shallowRef} from "vue";
import {Ion, Viewer, Terrain} from 'cesium'
import "cesium/Build/Cesium/Widgets/widgets.css";
import * as Cesium from "cesium";

// 服务器上托管 CesiumJS 静态文件的 URL。
window.CESIUM_BASE_URL = '/Cesium';
// 您的访问令牌可在以下位置找到：https://ion.cesium.com/tokens。
// 将“your_access_token”替换为您的铯离子访问令牌。
Ion.defaultAccessToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIyNjJhZWE3NC1iYjY2LTQwZjAtODc0YS0zZTdlMjRmNTE5ZDEiLCJpZCI6MjA1NjY1LCJpYXQiOjE3MTE5MzExMzB9.efKdT634nrROZLOR-GmU5gvPmnlCDsiHDTkCYlU4SXA';
// 设置默认视角为中国
Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(
    114.0,
    22.0,
    117.0,
    25.0
);

/* 创建视图（查看器） */
const cesiumViewer = shallowRef()

async function createViewer() {
  const viewer = new Viewer('cesiumContainer', {
    animation: false, // 隐藏左下角动画部件
    timeline: false, // 隐藏底部时间轴部件
    fullscreenButton: false, // 隐藏右下角全屏按钮部件
    // creditDisplay: false, // 隐藏屏幕和灯箱中显示的制作人员名单。
    geocoder: false, // 隐藏右上角搜索按钮部件
    homeButton: false, // 隐藏右上角 Home 按钮部件
    sceneModePicker: false, // 隐藏右上角场景模式按钮部件
    baseLayerPicker: false, // 隐藏右上角图层选择按钮部件
    navigationHelpButton: false, // 隐藏右上角帮助按钮部件
    // vrButton: false, // 显示右下角 VRButton 按钮部件
    // selectionIndicator: false, // 隐藏点击要素之后显示的选择指示器
    // infoBox: false, // 隐藏点击要素之后显示的信息框
    // skyBox: false, // 天空盒，取消默认天空盒、太阳、月亮
    // skyAtmosphere: false, // 天空大气层，取消大气层效果 蔚蓝的天空，以及地球边缘的光芒
    // globe: false, // 要在场景中使用的地球仪。如果设置为 false ，则不会添加任何地球仪，并且默认情况下将隐藏天空大气层。
    // projectionPicker: true, // 显示右上角投影选择按钮部件
    // https://cesium.com/blog/2018/01/24/cesium-scene-rendering-performance/
    requestRenderMode: true, // 仅在需要时才会渲染帧，具体取决于场景中的更改。启用可减少应用程序的 CPU/GPU 使用率，并在移动设备上使用更少的电池
    maximumRenderTimeChange: Infinity, // 允许的最大渲染时间差，以秒为单位。
    terrain: Terrain.fromWorldTerrain({
      requestVertexNormals: true, // 请求其他照明信息
      requestWaterMask: true, // 请求每个磁贴的水掩码
    })
  });
  console.log('视图查看器：', viewer);
  // 显式渲染新帧
  // viewer.scene.requestRender();
  // 启用光照
  viewer.scene.globe.enableLighting = true;
  // 隐藏底部 Cesium logo 与 attribution 标注信息部件
  // viewer.cesiumWidget.creditContainer.style.display = 'none'
  viewer.bottomContainer.style.display = 'none'

  cesiumViewer.value = viewer

  // 去除控制台 infoBox 沙箱警告报错 （allow-scripts 不安全，容易导致 XSS 攻击）
  // Blocked script execution in 'about:blank' because the document's frame is sandboxed and the 'allow-scripts' permission is not set.
  let oInfoBoxSandBoxed = document.querySelector('.cesium-infoBox-iframe');
  if (oInfoBoxSandBoxed) {
    oInfoBoxSandBoxed.setAttribute('sandbox', 'allow-scripts allow-same-origin allow-popups allow-forms')
    oInfoBoxSandBoxed.setAttribute('src', '')
  }
}

onMounted(() => {
  createViewer()

  // 自定义全屏按钮
  const oBtnFullscreen = document.querySelector('#btnFullscreen');
  const fullscreenButton = new Cesium.FullscreenButton(oBtnFullscreen, document.body);
  // 获取全屏按钮
  const oCesiumFullscreenButton = fullscreenButton.container.children[0]
  oCesiumFullscreenButton.title = '全屏'
  // 鼠标移入按钮，修改 tooltip
  fullscreenButton.container.addEventListener('mouseenter', () => {
    if (fullscreenButton.viewModel.isFullscreen) {
      oCesiumFullscreenButton.title = '退出全屏'
    } else {
      oCesiumFullscreenButton.title = '全屏'
    }
  })

  // 自定义Home按钮
  const oBtnHome = document.querySelector('#btnHome');
  const homeButton = new Cesium.HomeButton(oBtnHome, cesiumViewer.value.scene, 3);
  // 修改 tooltip
  // homeButton.container.children[0].title = '首页'
  homeButton.viewModel.tooltip = '首页'

  // 自定义基本图层选择按钮
  /*const oBtnBaseLayerPicker = document.querySelector('#btnBaseLayerPicker');
  const imageryViewModels = [];
  imageryViewModels.push(new Cesium.ProviderViewModel({
    name: "Open\u00adStreet\u00adMap",
    iconUrl: Cesium.buildModuleUrl("Widgets/Images/ImageryProviders/openStreetMap.png"),
    tooltip: "OpenStreetMap (OSM) is a collaborative project to create a free editable \
map of the world.\nhttp://www.openstreetmap.org",
    creationFunction: function() {
      return new Cesium.OpenStreetMapImageryProvider({
        url: "https://tile.openstreetmap.org/"
      });
    }
  }));
  imageryViewModels.push(new Cesium.ProviderViewModel({
    name: "Earth at Night",
    iconUrl: Cesium.buildModuleUrl("Widgets/Images/ImageryProviders/blackMarble.png"),
    tooltip: "The lights of cities and villages trace the outlines of civilization \
in this global view of the Earth at night as seen by NASA/NOAA's Suomi NPP satellite.",
    creationFunction: function() {
      return Cesium.IonImageryProvider.fromAssetId(3812);
    }
  }));
  imageryViewModels.push(new Cesium.ProviderViewModel({
    name: "Natural Earth\u00a0II",
    iconUrl: Cesium.buildModuleUrl("Widgets/Images/ImageryProviders/naturalEarthII.png"),
    tooltip: "Natural Earth II, darkened for contrast.\nhttp://www.naturalearthdata.com/",
    creationFunction: function() {
      return Cesium.TileMapServiceImageryProvider.fromUrl(
          Cesium.buildModuleUrl("Assets/Textures/NaturalEarthII")
      );
    }
  }));
  const baseLayerPicker = new Cesium.BaseLayerPicker(oBtnBaseLayerPicker, {
    globe: cesiumViewer.value.scene.globe,
    imageryProviderViewModels: imageryViewModels
    // imageryProviderViewModels: [],
    // selectedImageryProviderViewModel: null,
    // terrainProviderViewModels: [],
    // selectedTerrainProviderViewModel: null
  })
  console.log(baseLayerPicker);*/
})
</script>
